const static = require("koa-static");
const mount = require("koa-mount");
const path = require("path");
const fs = require("fs");

//遍历目录
const ergodicDir = (entry, base = "/") => {
  let target = [{ url: base || "/", path: entry }];
  function loopSearch(dir, basePath) {
    let dirs = fs.readdirSync(dir);
    dirs.forEach((child) => {
      let filePath = path.join(dir, child);
      let stat = fs.statSync(filePath);
      if (stat.isDirectory() === true) {
        const url = basePath === "/" ? `/${child}` : `${basePath}/${child}`;
        target.push({
          url,
          path: filePath,
        });
        loopSearch(filePath, url);
      }
    });
  }
  loopSearch(entry, base);
  return target;
};
module.exports = (app, { entry, options = {} }, log = true) => {
  if (!entry) {
    throw new Error("静态资源入口属性必填");
  }
  let targetPaths = [];
  if (entry instanceof Array) {
    entry.forEach((ety) => {
      targetPaths = targetPaths.concat(ergodicDir(ety.path, ety.base));
    });
  } else if (entry instanceof String) {
    targetPaths = ergodicDir(entry);
  }
  targetPaths.forEach((dir) => {
    if (log) {
      console.log("STATIC PATH:", dir.url);
    }
    app.use(mount(`${dir.url}`, static(dir.path, options)));
  });
};
